/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-14 18:32:16
 * @LastEditors: 周海 zhouhaib@yonyou.com
 * @LastEditTime: 2022-12-14 19:23:22
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { addRole, delRole, getRole, updateRole } from '@/api/system/role';
import { addRoleOrg, delRoleOrg, delRoleOrgByRoleId } from '@/api/system/roleOrg';
import { addRolePost, delRolePost, delRolePostByRoleId } from '@/api/system/rolePost';
import { addRoleUser, delRoleUser, delRoleUserByRoleId } from '@/api/system/roleUser';
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { SysPostDomain } from '@/type.d/system/post';
import { SysRoleDomain } from '@/type.d/system/role';
import { SysRoleOrgDomain } from '@/type.d/system/roleorg';
import { SysRolePostDomain } from '@/type.d/system/rolePost';
import { SysRoleUserDomain } from '@/type.d/system/roleUser';
import { Button, Col, Form, Input, InputNumber, Modal, Radio, Row, Space, Tabs, TreeSelect } from 'antd';
import React, { useEffect, useState } from 'react'
import RoleOrg from './components/roleOrg';
import RolePost from './components/rolePost';
import RoleUser from './components/roleUser';
import RoleTransfer from './components/transfer';
import TreeTransfer from './components/treeTransfer';
import './index.less';

interface RoleCardProp {
    userOptions?: any[],
    postOptions?: any[],
    orgs?: any[],
    corpTreeOptions?: any[],
    sysNormalDisableOptions?: any[],
    /**
     * 卡片数据 受控
     */
    cardData: SysRoleDomain;
    /**
     * 卡片新增时的默认数据
     */
    newdata?: SysRoleDomain;
    /**
     * 列表数据
     */
    tableListDataSource: SysRoleDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: SysRoleDomain[]) => void;

    setIsedit?: (isedit: boolean) => void;

    isedit?: boolean;
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
const RoleCard: React.FC<RoleCardProp> = (props: RoleCardProp) => {
    const { userOptions = [], postOptions = [], orgs = [], corpTreeOptions = [], sysNormalDisableOptions = [], cardData, newdata = {}, tableListDataSource, setTableListDataSource, setIsedit, isedit = false, onBack } = props;
    const { layoutStore, userStore } = useStore();
    const [formRef] = Form.useForm<SysRoleDomain>();
    const [selectdata, setSelectdata] = useState<SysRoleDomain>(cardData);
    const [oldSelectdata, setOldSelectdata] = useState<SysRoleDomain>();//编辑状态临时保存选中的数据

    const [roleOrgs, setRoleOrgs] = useState<SysRoleOrgDomain[]>([]);//卡片状态下角色与组织关系
    const [oldRoleOrgs, setOldRoleOrgs] = useState<SysRoleOrgDomain[]>([]);//卡片状态下角色与组织关系

    const [rolePosts, setRolePosts] = useState<SysRolePostDomain[]>([]);//卡片状态下角色与岗位关系
    const [oldRolePosts, setOldRolePosts] = useState<SysRolePostDomain[]>([]);//卡片状态下角色与岗位关系

    const [roleUsers, setRoleUsers] = useState<SysRoleUserDomain[]>([]);//卡片状态下角色与人员关系
    const [oldRoleUsers, setOldRoleUsers] = useState<SysRoleUserDomain[]>([]);//卡片状态下角色与人员关系


    const [activeKey, setActiveKey] = useState<string>('1');

    const [isTranOpen, setIsTranOpen] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

    /**
     * 表单字段配置
     */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6} hidden>
                <Form.Item name="roleId" label="角色ID">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="pkCorp" label="所属公司" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]} >
                    <TreeSelect treeData={corpTreeOptions} />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="roleName" label="角色名称" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]} >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="roleKey" label="角色权限字符串" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]} >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="roleSort" label="显示顺序" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]} >
                    <InputNumber />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="status" label="角色状态" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]} >
                    <Radio.Group options={sysNormalDisableOptions} />
                </Form.Item>
            </Col>
            <Col md={24} xl={24}>
                <Form.Item name="remark" label="备注">
                    <Input.TextArea />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="createBy" label="创建者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dateTime" label="创建时间">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateBy" label="更新者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateTime" label="更新时间">
                    <Input disabled />
                </Form.Item>
            </Col>
        </Row>;


    const addCardData = (_cardData: SysRoleDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setOldRoleOrgs(roleOrgs)
        setOldRolePosts(rolePosts)
        setOldRoleUsers(roleUsers)
        setRoleOrgs([])
        setRolePosts([])
        setRoleUsers([])
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setOldRoleOrgs(roleOrgs)
        setOldRolePosts(rolePosts)
        setOldRoleUsers(roleUsers)
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
        setRoleOrgs(oldRoleOrgs)
        setRolePosts(oldRolePosts)
        setRoleUsers(oldRoleUsers)
        setOldRoleOrgs([])
        setOldRolePosts([])
        setOldRoleUsers([])
    }

    const intCardData = (_cardData: SysPostDomain) => {
        if (_cardData.roleId) {
            layoutStore.OpenSpanning()
            getRole(_cardData.roleId).then((res) => {
                const info = res.data;
                setSelectdata({ ...info.datas })
                setOldSelectdata({ ...info.datas })
                setRoleOrgs(info.roleorgs)
                setRolePosts(info.roleposts)
                setRoleUsers(info.roleusers)
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [cardData])

    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef.setFieldsValue(selectdata);
        } else {
            formRef.setFieldsValue({});
        }
    }, [selectdata])

    const onDelete = (dedata: SysRoleDomain) => {
        if (dedata.roleId) {
            layoutStore.OpenSpanning()
            delRole(dedata.roleId).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setRoleOrgs([])
                setRolePosts([])
                setRoleUsers([])
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.roleId !== dedata.roleId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    const cardbuttons = (
        <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata })
                }}
            >
                新增
            </Button>
            <Button
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.roleId ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.roleId ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>

    )

    const editbuttions = (
        <Space>
            <Button
                size='small'
                key="save"
                type="primary"
                onClick={() => {
                    onSave()
                }}
            >
                保存
            </Button>
            <Button
                size='small'
                key="cancel"
                type="primary"
                onClick={() => {
                    resetCardData()
                    setIsedit?.(false)
                }}
            >
                取消
            </Button>
        </Space>
    )

    const onSave = () => {
        formRef.validateFields().then(() => {
            const data: SysRoleDomain = formRef.getFieldsValue?.() || {};
            if (!selectdata.roleId) {//新增
                layoutStore.OpenSpanning()
                addRole({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])

                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updateRole({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.roleId === res.data.roleId) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })
    }

    const operations = () => {
        if(!isedit){
            if (activeKey === '1') {
                return <Button size='small'
                    key="add"
                    type="primary"
                    onClick={() => { setIsTranOpen(true) }}>分配用户</Button>
            } else if (activeKey === '2') {
                return <Button size='small'
                    key="add"
                    type="primary"
                    onClick={() => { setIsTranOpen(true) }}>分配岗位</Button>
            } else if (activeKey === '3') {
                return <Button size='small'
                    key="add"
                    type="primary"
                    onClick={() => { setIsModalOpen(true) }}>分配组织</Button>
            }
        }
        
    }


    const transSave = (targetKeys: string[]) => {
        if (activeKey === '1') {
            setIsTranOpen(false)
            //角色与用户分配关系
            const roleusers = targetKeys.map((key) => {
                return {
                    roleId: selectdata.roleId,
                    userId: key
                }
            })
            if (roleusers && roleusers.length > 0) {
                addRoleUser(roleusers).then((res) => {
                    setRoleUsers(res.data)
                })
            } else {
                if (selectdata.roleId) {
                    delRoleUserByRoleId(selectdata.roleId).then(() => {
                        setRoleUsers([])
                    })
                }

            }

        } else if (activeKey === '2') {
            setIsTranOpen(false)
            //角色与岗位分配关系
            const roleposts = targetKeys.map((key) => {
                return {
                    roleId: selectdata.roleId,
                    postId: key
                }
            })
            if (roleposts && roleposts.length > 0) {
                addRolePost(roleposts).then((res) => {
                    setRolePosts(res.data)
                })
            } else {
                if (selectdata.roleId) {
                    delRolePostByRoleId(selectdata.roleId).then(() => {
                        setRolePosts([])
                    })
                }
            }
        } else if (activeKey === '3') {
            setIsModalOpen(false)
            if (targetKeys && targetKeys.length > 0) {
                //角色与组织分配关系
                const savedatas = orgs.filter((org) => {
                    const target = targetKeys.filter((key) => { return org.key === key })
                    return target.length > 0
                })
                addRoleOrg(savedatas.map((item) => {
                    return {
                        roleId: selectdata.roleId,
                        orgId: item.key,
                        orgType: item.orgType,
                        pkOrg: item.pkOrg
                    }
                })).then((res) => {
                    setRoleOrgs(res.data)
                })
            } else {
                if (selectdata.roleId) {
                    delRoleOrgByRoleId(selectdata.roleId).then(() => {
                        setRoleOrgs([])
                    })
                }
            }

        }

    }

    const onDeleteRoleUser = (roleUser: SysRoleUserDomain) => {
        if (roleUser.pkRoleUser) {
            delRoleUser(roleUser.pkRoleUser).then(() => {
                setRoleUsers(roleUsers.filter((item) => {
                    return item.pkRoleUser !== roleUser.pkRoleUser
                }))

            })
        }

    }


    const onDeleteRolePost = (rolePost: SysRolePostDomain) => {
        if (rolePost.rolePostId) {
            delRolePost(rolePost.rolePostId).then(() => {
                setRolePosts(rolePosts.filter((item) => {
                    return item.rolePostId !== rolePost.rolePostId
                }))

            })
        }

    }

    const onDeleteRoleOrg = (roleOrg: SysRoleOrgDomain) => {
        if (roleOrg.roleOrgId) {
            delRoleOrg(roleOrg.roleOrgId).then(() => {
                setRoleOrgs(roleOrgs.filter((item) => {
                    return item.roleOrgId !== roleOrg.roleOrgId
                }))

            })
        }

    }


    return (
        <>
            <BillCard
                formid='roleId'
                key={'roleCard'}
                cardItem={cardItems}
                formRef={formRef}
                isedit={isedit}
                extraButton={isedit ? editbuttions : cardbuttons}
                onBack={onBack}
                title={'角色管理'} >
                <Tabs defaultActiveKey="1"
                    onChange={setActiveKey}
                    tabBarExtraContent={operations()}
                    items={[
                        {
                            label: `已分配用户`,
                            key: '1',
                            style: { flex: 1 },
                            children: <RoleUser dataSources={roleUsers} userOptions={userOptions} onDelete={onDeleteRoleUser} />
                        },
                        {
                            label: `已分配岗位`,
                            key: '2',
                            children: <RolePost dataSources={rolePosts} postOptions={postOptions} onDelete={onDeleteRolePost} />
                        },
                        {
                            label: `已分配组织`,
                            key: '3',
                            children: <RoleOrg dataSources={roleOrgs} orgOptions={orgs} onDelete={onDeleteRoleOrg} />
                        },
                    ]} />
            </BillCard>
            <RoleTransfer
                isModalOpen={isTranOpen}
                dataSources={activeKey === '1' ? userOptions : postOptions}
                targetKeys={activeKey === '1' ? roleUsers.map((item) => {
                    return item.userId || ""
                }) : rolePosts.map((item) => {
                    return item.postId || ""
                })}
                onCancel={() => { setIsTranOpen(false); }}
                onOk={transSave} />
            <TreeTransfer
                dataSource={orgs}
                targetKeys={roleOrgs ? roleOrgs.map((item) => {
                    return item.orgId || ''
                }) : []}
                isModalOpen={isModalOpen}
                onOk={transSave}
                onCancel={() => setIsModalOpen(false)} />
        </>
    )
}
export default RoleCard;